<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="注意！只能为第三类分级设置相关参数"
                type="warning"
                :closable="false"
                show-icon>
      </el-alert>

      <!-- 选择商品分类区 -->
      <el-row class="cat_opt">
        <el-col>
          <span class="cat_span">选择商品分类:</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader v-model="selectedCateKeys"
                       :options="catelist"
                       expand-change="hover"
                       :props="cateProps"
                       @change="handleChange"></el-cascader>
        </el-col>
      </el-row>

      <!-- tab页标签区 -->
      <template>
        <el-tabs v-model="activeName"
                 @tab-click="handleTabClick">
          <el-tab-pane label="动态参数"
                       name="many">
            <el-button type="primary"
                       size="mini"
                       :disabled="isBtnDisabled"
                       @click="showAddDialog()">添加参数</el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyTabData"
                      border
                      stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,index) in scope.row.attr_vals"
                          :key="index"
                          class="cat_tag"
                          closable
                          @close="handleClosed(scope.row,index)">{{item}}</el-tag>
                  <el-input class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else
                             class="button-new-tag"
                             size="small"
                             @click="showInput(scope.row)">+ 新的标签</el-button>
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称"
                               prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary"
                             icon="el-icon-edit"
                             size="mini"
                             @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger"
                             icon="el-icon-delete"
                             size="mini"
                             @click="removeParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性"
                       name="only">
            <el-button type="primary"
                       size="mini"
                       :disabled="isBtnDisabled"
                       @click="showAddDialog()">添加属性</el-button>
            <!-- 静态属性表格 -->
            <el-table :data="onlyTabData"
                      border
                      stripe>
              <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,index) in scope.row.attr_vals"
                          :key="index"
                          class="cat_tag"
                          closable
                          @close="handleClosed(scope.row,index)">{{item}}</el-tag>
                  <el-input class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else
                             class="button-new-tag"
                             size="small"
                             @click="showInput(scope.row)">+ 新的标签</el-button>
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="属性名称"
                               prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary"
                             icon="el-icon-edit"
                             size="mini"
                             @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger"
                             icon="el-icon-delete"
                             size="mini"
                             @click="removeParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog :title="'添加'+titleText"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addDialogClosed()">
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="100px">
        <el-form-item :label="titleText"
                      prop="attr_name">
          <el-input v-model="addForm.attr_name"
                    clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addParams()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog :title="'修改'+titleText"
               :visible.sync="editDialogVisible"
               width="50%"
               @close="editDialogClosed()">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="100px">
        <el-form-item :label="titleText"
                      prop="attr_name">
          <el-input v-model="editForm.attr_name"
                    clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      catelist: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      }, // 商品列表数组
      // 级联选择器的配置对象
      selectedCateKeys: [], // 级联选择框双向绑定的数组
      activeName: "many", // 被激活的页签名称(name)
      manyTabData: [],  // 动态参数的数据
      onlyTabData: [],  //静态数据的数据
      addDialogVisible: false,//添加对话框的显示/隐藏
      addForm: {
        attr_name: ""
      }, // 添加菜单的表单数据对象
      addFormRules: { //添加表单的验证规则对象
        attr_name: [
          {
            required: true, message: "请输入参数名称", trigger: "blur"
          }
        ]
      },
      // 编辑对话框的显示
      editDialogVisible: false,
      // 修改对话框数据
      editForm: {
        attr_name: ""
      },
      // 编辑对话框的验证规则
      editFormRules: {
        attr_name: [
          {
            required: true, message: "请输入参数名称", trigger: "blur"
          }
        ]
      }
    }
  },
  methods: {
    // 获取所有的商品分类
    async getCateList () {
      const { data: res } = await this.$ajax.get("/categories")
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类列表失败")
      }
      this.catelist = res.data
    },
    // 分类名称级联选择框改变的时候会触发
    async handleChange () {
      this.getParamsData()
    },
    // Tab页签点击事件的处理函数
    handleTabClick () {
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData () {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return
      }

      //选中的三级分类
      const { data: res } = await this.$ajax.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败")
      }

      // 将数据列表中的attr_vals按照" "进行分割然后重新赋值，方便后续进行tag展示
      res.data.forEach(item => {
        /* item.attr_vals = (-1 != item.attr_vals.indexOf("-")) ? item.attr_vals.split("-") : []
        item.attr_vals.forEach(values => {
          values = values ? values.split(" ") : []
        }) */
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
        // 控制文本的显示/隐藏
        item.inputVisible = false
        //文本框中输入的值
        item.inputValue = ""
      })

      // 判断是获取的哪个tab页的数据
      if (this.activeName === "many") {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // 点击打开添加对话框
    showAddDialog () {
      this.addDialogVisible = true
    },
    // 关闭添加参数对话框执行的函数
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击添加参数的确定按钮执行的函数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$ajax.post(`/categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          })

        if (res.meta.status !== 201) {
          this.addDialogVisible = false
          this.getParamsData()
          return this.$message.error(`添加${this.titleText}错误`)
        }
        this.$message.success(`添加${this.titleText}成功`)
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 参数名称表格中的编辑按钮,展示编辑对话框
    async showEditDialog (attr_id) {
      // 查询当前参数的信息
      const { data: res } = await this.$ajax.get(`/categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        })
      if (res.meta.status !== 200) {
        return this.$message.error("查询当前信息失败")
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改对话框关闭时调用此函数
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑对话框点击确定提交数据
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$ajax.put(`/categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          })

        if (res.meta.status !== 200) {
          this.editDialogVisible = false
          this.getParamsData()
          return this.$message.error(`修改${this.titleText}错误`)
        }
        this.$message.success(`修改${this.titleText}成功`)
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 删除动态参数/静态属性的一行参数
    removeParams (attr_id) {
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async (res) => {
        const { data: result } = await this.$ajax.delete(`categories/${this.cateId}/attributes/${attr_id}`)

        if (result.meta.status !== 200) {
          return this.$message.error(`删除${this.titleText}错误`)
        }
        this.getParamsData()

        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch((err) => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    // 输入框失去焦点的时候或者按下enter触发
    async handleInputConfirm (row) {
      // 判断输入框中的文本是否为空
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ""
        row.inputVisible = false
        return
      }

      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ""
      row.inputVisible = false

      // 输入的内容是正确的
      this.saveAttrVals(row)
    },
    // 发送添加/删除标签操作函数
    async saveAttrVals (row) {

      const { data: res } = await this.$ajax.put(`/categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        })

      if (res.meta.status !== 200) {
        return this.$message.error("添加标签失败")
      }
    },
    // 点击按钮，展示文本输入框
    showInput (row) {
      row.inputVisible = true

      /* 
        自动获得输入框中的焦点
        $nextTick作用：当页面所有的元素都被加载出来之后执行指定的函数
      */
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 点击标签删除
    handleClosed (row, i) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  created () {
    this.getCateList();
  },
  computed: {
    // 如果按钮需要被禁用就返回true,否则选择false
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        // 没有选择3级分类
        return true
      } else {
        return false
      }
    },
    // 当前选中的三级分类的id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 动态计算标题的本本
    titleText () {
      if (this.activeName === "many") {
        return "动态参数"
      } else {
        return "静态属性"
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.cat_span {
  margin-right: 20px;
}

.cat_tag {
  margin-right: 20px;
  margin-top: 10px;
}

.input-new-tag {
  width: 150px;
}
</style>